﻿using System;
using System.Linq;
using _5E.Infrastructure.Logging;
using _5E.Infrastructure.Querying;
using _5E.Infrastructure.String;
using StoneAge.Contract;
using StoneAge.DataContract.Extension;
using StoneAge.DataContract.Messaging;
using StoneAge.Models.Entity;
using StoneAge.Models.Repository;

namespace StoneAge.Service
{
    public class AccountService : IAccountService
    {
        private IAccountRepository m_accountRespository = null;
        private IRoleRepository m_roleRepository = null;

        public AccountService(IAccountRepository accountRepository, IRoleRepository roleRepository)
        {
            m_accountRespository = accountRepository;
            m_roleRepository = roleRepository;
        }

        public LoginResponse LoginBy(LoginRequest request)
        {
            LoginResponse response = new LoginResponse();

            Query query = new Query();
            query.Add<Account>(a => a.Name, CriteriaOperator.Eq, request.Name);
            try
            {
                var accounts = m_accountRespository.FindBy(query);

                if (1 == accounts.Count())
                {
                    Account account = accounts.First();
                    if (account.Pwd.CompareByBCrypt(request.Pwd))
                    {
                        response.AccountId = account.Id;
                        response.Roles = account.Roles.ConvertToRoleCatalogView();
                        return response;
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingFactory.Logger.Log(ex);
            }

            response.Success = false;
            response.Message = "用户名或者密码错误!";
            return response;
        }
    }
}
